<template>
  <div class="wallet-page">
    <!-- 钱包头部信息 -->
    <div class="wallet-header">
      <div class="balance-card">
        <div class="balance-info">
          <div class="balance-label">我的书币</div>
          <div class="balance-amount">{{ walletInfo.balance || userStore.user?.coins || userStore.user?.balance || 0 }}</div>
          <div class="balance-note">1书币 = 1分钱</div>
        </div>
        <div class="balance-actions">
          <el-button type="primary" size="large" @click="showRechargeDialog">
            <el-icon><Plus /></el-icon>
            充值
          </el-button>
        </div>
      </div>
      
      <div class="wallet-stats">
        <div class="stat-item">
          <div class="stat-value">{{ walletInfo.totalRecharge || 0 }}</div>
          <div class="stat-label">累计充值</div>
        </div>
        <div class="stat-item">
          <div class="stat-value">{{ walletInfo.totalConsumption || 0 }}</div>
          <div class="stat-label">累计消费</div>
        </div>
        <div class="stat-item">
          <div class="stat-value">{{ userStore.user?.level || 1 }}</div>
          <div class="stat-label">用户等级</div>
        </div>
      </div>
    </div>

    <!-- 快捷功能 -->
    <div class="quick-actions">
      <div class="action-item" @click="showRecordsDialog">
        <el-icon><Document /></el-icon>
        <span>交易记录</span>
      </div>
      <div class="action-item">
        <el-icon><QuestionFilled /></el-icon>
        <span>帮助中心</span>
      </div>
    </div>

    <!-- 最近交易 -->
    <div class="recent-transactions">
      <div class="section-header">
        <h3>最近交易</h3>
        <el-button text @click="showRecordsDialog">查看全部</el-button>
      </div>
      <div class="transaction-list">
        <div
          v-for="record in recentRecords"
          :key="record.id"
          class="transaction-item"
        >
          <div class="transaction-icon">
            <el-icon v-if="record.type === 'recharge'" color="#67c23a"><Plus /></el-icon>
            <el-icon v-else color="#f56c6c"><Minus /></el-icon>
          </div>
          <div class="transaction-info">
            <div class="transaction-desc">{{ record.description }}</div>
            <div class="transaction-time">{{ formatTime(record.createdAt) }}</div>
          </div>
          <div class="transaction-amount" :class="record.type === 'recharge' ? 'income' : 'expense'">
            {{ record.type === 'recharge' ? '+' : '-' }}{{ record.amount }}
          </div>
        </div>
        <div v-if="recentRecords.length === 0" class="empty-state">
          <el-icon><DocumentRemove /></el-icon>
          <p>暂无交易记录</p>
        </div>
      </div>
    </div>

    <!-- 充值对话框 -->
    <el-dialog
      v-model="rechargeDialogVisible"
      title="选择充值套餐"
      width="600px"
      :before-close="handleRechargeDialogClose"
    >
      <div class="recharge-packages">
        <div
          v-for="pkg in rechargePackages"
          :key="pkg.id"
          class="package-item"
          :class="{ active: selectedPackage?.id === pkg.id, popular: pkg.isPopular }"
          @click="selectPackage(pkg)"
        >
          <div v-if="pkg.isPopular" class="popular-badge">推荐</div>
          <div class="package-info">
            <div class="package-amount">{{ pkg.amount }}书币</div>
            <div v-if="pkg.bonus > 0" class="package-bonus">+{{ pkg.bonus }}赠送</div>
            <div class="package-desc">{{ pkg.description }}</div>
          </div>
          <div class="package-price">
            <div class="current-price">￥{{ pkg.price }}</div>
          </div>
        </div>
      </div>
      
      <div class="payment-methods">
        <div class="method-title">选择支付方式</div>
        <div class="method-list">
          <div
            v-for="method in paymentMethods"
            :key="method.value"
            class="payment-method"
            :class="{ active: selectedPaymentMethod === method.value }"
            @click="selectPaymentMethod(method.value)"
          >
            <el-icon>
              <component :is="method.icon" />
            </el-icon>
            <span>{{ method.label }}</span>
          </div>
        </div>
      </div>
      
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="rechargeDialogVisible = false">取消</el-button>
          <el-button type="primary" :disabled="!selectedPackage" @click="proceedToPayment">
            下一步
          </el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 支付密码确认对话框 -->
    <el-dialog
      v-model="paymentPasswordDialogVisible"
      title="确认支付"
      width="400px"
      :before-close="handlePaymentPasswordDialogClose"
    >
      <div class="payment-summary">
        <div class="payment-amount">￥{{ selectedPackage?.price }}</div>
        <div class="payment-desc">{{ selectedPackage?.description }}</div>
        <div class="payment-coins">获得书币：{{ selectedPackage ? selectedPackage.amount + selectedPackage.bonus : 0 }}</div>
        <div class="payment-method">支付方式：{{ getPaymentMethodName(selectedPaymentMethod) }}</div>
      </div>
      
      <el-form ref="paymentPasswordFormRef" :model="paymentPasswordForm" :rules="paymentPasswordRules">
        <el-form-item label="验证密码" prop="password">
          <el-input
            v-model="paymentPasswordForm.password"
            type="password"
            show-password
            placeholder="请输入密码："
            maxlength="5"
            @keyup.enter="handlePaymentSubmit"
          />
        </el-form-item>
      </el-form>
      
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="paymentPasswordDialogVisible = false">取消</el-button>
          <el-button type="primary" :loading="processing" @click="handlePaymentSubmit">
            确认支付
          </el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 交易记录对话框 -->
    <el-dialog
      v-model="recordsDialogVisible"
      title="交易记录"
      width="800px"
    >
      <div class="records-content">
        <div class="records-filter">
          <el-select v-model="recordsFilter" placeholder="筛选类型" style="width: 150px">
            <el-option label="全部" value="all" />
            <el-option label="充值" value="recharge" />
            <el-option label="消费" value="chapter" />
            <el-option label="VIP" value="vip" />
          </el-select>
        </div>
        
        <div class="records-list">
          <div
            v-for="record in filteredRecords"
            :key="record.id"
            class="record-item"
          >
            <div class="record-icon">
              <el-icon v-if="record.type === 'recharge'" color="#67c23a"><Plus /></el-icon>
              <el-icon v-else color="#f56c6c"><Minus /></el-icon>
            </div>
            <div class="record-info">
              <div class="record-desc">{{ record.description }}</div>
              <div class="record-meta">
                <span>{{ formatTime(record.createdAt) }}</span>
                <span class="record-status" :class="record.status">
                  {{ getStatusText(record.status) }}
                </span>
              </div>
            </div>
            <div class="record-amount" :class="record.type === 'recharge' ? 'income' : 'expense'">
              {{ record.type === 'recharge' ? '+' : '-' }}{{ record.amount }}
            </div>
          </div>
          
          <div v-if="filteredRecords.length === 0" class="empty-state">
            <el-icon><DocumentRemove /></el-icon>
            <p>暂无相关记录</p>
          </div>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { Plus, Minus, Document, QuestionFilled, DocumentRemove } from '@element-plus/icons-vue'
import { useUserStore } from '@/stores/user'
import { 
  getRechargePackages, 
  createRechargeOrder, 
  // getTransactionRecords, // 暂时注释，等数据库修复后启用
  getWalletInfo,
  type RechargePackage,
  type TransactionRecord
} from '@/api/payment'

const userStore = useUserStore()

// 响应式数据
const rechargeDialogVisible = ref(false)
const paymentPasswordDialogVisible = ref(false)
const recordsDialogVisible = ref(false)
const processing = ref(false)
const loading = ref(false)

const selectedPackage = ref<RechargePackage | null>(null)
const selectedPaymentMethod = ref<'alipay' | 'wechat' | 'mock'>('alipay')
const recordsFilter = ref('all')

// 数据
const rechargePackages = ref<RechargePackage[]>([])
const transactionRecords = ref<TransactionRecord[]>([])
const walletInfo = ref({
  balance: 0,
  totalRecharge: 0,
  totalConsumption: 0
})

// 表单数据
const paymentPasswordForm = ref({
  password: ''
})

// 表单引用
const paymentPasswordFormRef = ref()

// 支付方式
const paymentMethods = [
  { value: 'alipay' as const, label: '支付宝', icon: 'Money' },
  { value: 'wechat' as const, label: '微信支付', icon: 'ChatDotRound' },
  { value: 'mock' as const, label: '模拟支付（测试）', icon: 'CreditCard' }
]

// 最近交易记录
const recentRecords = computed(() => 
  transactionRecords.value.slice(0, 5)
)

// 筛选后的交易记录
const filteredRecords = computed(() => {
  if (recordsFilter.value === 'all') {
    return transactionRecords.value
  }
  
  let filterType = recordsFilter.value
  if (filterType === 'chapter') {
    filterType = 'consumption'
  }
  
  return transactionRecords.value.filter(record => record.type === filterType)
})

// 表单验证规则
const paymentPasswordRules = {
  password: [
    { required: true, message: '请输入验证密码', trigger: 'blur' },
    { pattern: /^\d{5}$/, message: '密码必须是5位数字', trigger: 'blur' }
  ]
}

// 加载数据
const loadData = async () => {
  try {
    loading.value = true
    
    // 并行加载数据
    const [packagesData, walletData] = await Promise.all([
      getRechargePackages(),
      getWalletInfo()
    ])
    
    rechargePackages.value = packagesData
    // 暂时跳过交易记录，等数据库表结构修复后再启用
    // transactionRecords.value = recordsData.records
    transactionRecords.value = []
    walletInfo.value = walletData
    
    // 更新用户store中的余额
    if (userStore.user) {
      userStore.user.coins = walletData.balance
      userStore.user.balance = walletData.balance
    }
    
  } catch (error) {
    console.error('加载数据失败:', error)
    ElMessage.error('加载数据失败')
  } finally {
    loading.value = false
  }
}

// 方法
const showRechargeDialog = () => {
  rechargeDialogVisible.value = true
}

const showRecordsDialog = async () => {
  recordsDialogVisible.value = true
  // 暂时显示空记录，等数据库表结构修复后再启用
  // try {
  //   const data = await getTransactionRecords({ limit: 100 })
  //   transactionRecords.value = data.records
  // } catch (error) {
  //   console.error('加载交易记录失败:', error)
  // }
  ElMessage.info('交易记录功能正在完善中...')
}

const selectPackage = (pkg: RechargePackage) => {
  selectedPackage.value = pkg
}

const selectPaymentMethod = (method: 'alipay' | 'wechat' | 'mock') => {
  selectedPaymentMethod.value = method
}

const proceedToPayment = () => {
  if (!selectedPackage.value) {
    ElMessage.warning('请选择充值套餐')
    return
  }
  
  paymentPasswordDialogVisible.value = true
  rechargeDialogVisible.value = false
  paymentPasswordForm.value.password = ''
}

const handlePaymentSubmit = async () => {
  if (!paymentPasswordFormRef.value) return
  
  const valid = await paymentPasswordFormRef.value.validate()
  if (!valid) return
  
  if (!selectedPackage.value) return
  
  try {
    processing.value = true
    
    // 创建充值订单
    const order = await createRechargeOrder({
      packageId: selectedPackage.value.id,
      paymentMethod: selectedPaymentMethod.value
    })
    
    if (selectedPaymentMethod.value === 'mock') {
      // 模拟支付已经在后端自动完成
      ElMessage.success('充值成功！')
      paymentPasswordDialogVisible.value = false
      
      // 重新加载数据
      await loadData()
    } else {
      // 真实支付，这里应该跳转到支付页面
      ElMessage.info('请完成支付')
      // 实际项目中可能需要跳转到支付页面或打开支付窗口
      console.log('支付URL:', order)
    }
    
  } catch (error: unknown) {
    console.error('支付失败:', error)
    const errorMessage = error instanceof Error ? error.message : '支付失败'
    ElMessage.error(errorMessage)
  } finally {
    processing.value = false
  }
}

const handleRechargeDialogClose = () => {
  selectedPackage.value = null
  selectedPaymentMethod.value = 'alipay'
}

const handlePaymentPasswordDialogClose = () => {
  paymentPasswordForm.value.password = ''
}

// 工具方法
const formatTime = (timeStr: string) => {
  const date = new Date(timeStr)
  const now = new Date()
  const diff = now.getTime() - date.getTime()
  
  if (diff < 60000) {
    return '刚刚'
  } else if (diff < 3600000) {
    return `${Math.floor(diff / 60000)}分钟前`
  } else if (diff < 86400000) {
    return `${Math.floor(diff / 3600000)}小时前`
  } else {
    return date.toLocaleDateString()
  }
}

const getPaymentMethodName = (method: string) => {
  const methodMap: Record<string, string> = {
    alipay: '支付宝',
    wechat: '微信支付',
    mock: '模拟支付',
    bank: '银行卡'
  }
  return methodMap[method] || method
}

const getStatusText = (status: string) => {
  const statusMap: Record<string, string> = {
    pending: '处理中',
    paid: '已完成',
    failed: '失败',
    cancelled: '已取消'
  }
  return statusMap[status] || status
}

// 生命周期
onMounted(() => {
  loadData()
})
</script>

<style lang="scss" scoped>
.wallet-page {
  padding: var(--spacing-lg);
  max-width: 1200px;
  margin: 0 auto;
}

.wallet-header {
  margin-bottom: var(--spacing-xl);
}

.balance-card {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  border-radius: var(--radius-xl);
  padding: var(--spacing-xl);
  color: white;
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: var(--spacing-lg);
  box-shadow: var(--shadow-lg);
}

.balance-info {
  .balance-label {
    font-size: var(--font-size-sm);
    opacity: 0.9;
    margin-bottom: var(--spacing-xs);
  }
  
  .balance-amount {
    font-size: var(--font-size-3xl);
    font-weight: bold;
    margin-bottom: var(--spacing-xs);
  }
  
  .balance-note {
    font-size: var(--font-size-xs);
    opacity: 0.8;
  }
}

.balance-actions {
  .el-button {
    background: rgba(255, 255, 255, 0.2);
    border: 1px solid rgba(255, 255, 255, 0.3);
    color: white;
    
    &:hover {
      background: rgba(255, 255, 255, 0.3);
    }
  }
}

.wallet-stats {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  gap: var(--spacing-lg);
}

.stat-item {
  background: var(--bg-primary);
  border: 1px solid var(--border-color);
  border-radius: var(--radius-lg);
  padding: var(--spacing-lg);
  text-align: center;
  box-shadow: var(--shadow-sm);
  
  .stat-value {
    font-size: var(--font-size-xl);
    font-weight: bold;
    color: var(--primary-color);
    margin-bottom: var(--spacing-xs);
  }
  
  .stat-label {
    font-size: var(--font-size-sm);
    color: var(--text-secondary);
  }
}

.quick-actions {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  gap: var(--spacing-md);
  margin-bottom: var(--spacing-xl);
}

.action-item {
  background: var(--bg-primary);
  border: 1px solid var(--border-color);
  border-radius: var(--radius-lg);
  padding: var(--spacing-lg);
  text-align: center;
  cursor: pointer;
  transition: all 0.3s ease;
  box-shadow: var(--shadow-sm);
  
  &:hover {
    box-shadow: var(--shadow-md);
    transform: translateY(-2px);
  }
  
  .el-icon {
    font-size: 24px;
    color: var(--primary-color);
    margin-bottom: var(--spacing-sm);
  }
  
  span {
    display: block;
    font-size: var(--font-size-sm);
    color: var(--text-primary);
  }
}

.recent-transactions {
  background: var(--bg-primary);
  border: 1px solid var(--border-color);
  border-radius: var(--radius-lg);
  padding: var(--spacing-lg);
  box-shadow: var(--shadow-sm);
}

.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: var(--spacing-lg);
  
  h3 {
    margin: 0;
    color: var(--text-primary);
  }
}

.transaction-list {
  .transaction-item {
    display: flex;
    align-items: center;
    padding: var(--spacing-md) 0;
    border-bottom: 1px solid var(--border-color);
    
    &:last-child {
      border-bottom: none;
    }
  }
  
  .transaction-icon {
    margin-right: var(--spacing-md);
    
    .el-icon {
      font-size: 20px;
    }
  }
  
  .transaction-info {
    flex: 1;
    
    .transaction-desc {
      font-size: var(--font-size-base);
      color: var(--text-primary);
      margin-bottom: 2px;
    }
    
    .transaction-time {
      font-size: var(--font-size-xs);
      color: var(--text-tertiary);
    }
  }
  
  .transaction-amount {
    font-size: var(--font-size-lg);
    font-weight: bold;
    
    &.income {
      color: #67c23a;
    }
    
    &.expense {
      color: #f56c6c;
    }
  }
}

.empty-state {
  text-align: center;
  padding: var(--spacing-xl);
  color: var(--text-tertiary);
  
  .el-icon {
    font-size: 48px;
    margin-bottom: var(--spacing-md);
  }
  
  p {
    margin: 0;
    font-size: var(--font-size-sm);
  }
}

// 对话框样式
.recharge-packages {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: var(--spacing-md);
  margin-bottom: var(--spacing-lg);
}

.package-item {
  position: relative;
  border: 2px solid var(--border-color);
  border-radius: var(--radius-lg);
  padding: var(--spacing-lg);
  cursor: pointer;
  transition: all 0.3s ease;
  
  &:hover {
    border-color: var(--primary-light);
    transform: translateY(-2px);
  }
  
  &.active {
    border-color: var(--primary-color);
    background: rgba(30, 58, 138, 0.05);
  }
  
  &.popular {
    border-color: var(--secondary-color);
  }
  
  .popular-badge {
    position: absolute;
    top: -8px;
    right: var(--spacing-md);
    background: var(--secondary-color);
    color: white;
    padding: 2px var(--spacing-sm);
    border-radius: var(--radius-sm);
    font-size: var(--font-size-xs);
  }
  
  .package-info {
    text-align: center;
    margin-bottom: var(--spacing-md);
    
    .package-amount {
      font-size: var(--font-size-xl);
      font-weight: bold;
      color: var(--text-primary);
      margin-bottom: var(--spacing-xs);
    }
    
    .package-bonus {
      color: var(--secondary-color);
      font-size: var(--font-size-sm);
      margin-bottom: var(--spacing-xs);
    }
    
    .package-desc {
      color: var(--text-secondary);
      font-size: var(--font-size-sm);
    }
  }
  
  .package-price {
    text-align: center;
    
    .current-price {
      font-size: var(--font-size-lg);
      font-weight: bold;
      color: var(--primary-color);
    }
    
    .original-price {
      font-size: var(--font-size-sm);
      color: var(--text-tertiary);
      text-decoration: line-through;
    }
  }
}

.payment-section {
  margin-top: var(--spacing-lg);
  
  h4 {
    margin-bottom: var(--spacing-md);
    color: var(--text-primary);
  }
}

.payment-methods {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  gap: var(--spacing-md);
}

.payment-method {
  border: 1px solid var(--border-color);
  border-radius: var(--radius-md);
  padding: var(--spacing-md);
  text-align: center;
  cursor: pointer;
  transition: all 0.3s ease;
  
  &:hover {
    border-color: var(--primary-light);
  }
  
  &.active {
    border-color: var(--primary-color);
    background: rgba(30, 58, 138, 0.05);
  }
  
  .el-icon {
    font-size: 24px;
    color: var(--primary-color);
    margin-bottom: var(--spacing-xs);
  }
  
  span {
    display: block;
    font-size: var(--font-size-sm);
    color: var(--text-primary);
  }
}

.payment-info {
  background: var(--bg-secondary);
  border-radius: var(--radius-md);
  padding: var(--spacing-lg);
  margin-bottom: var(--spacing-lg);
  text-align: center;
  
  .payment-amount {
    font-size: var(--font-size-xl);
    font-weight: bold;
    color: var(--primary-color);
    margin-bottom: var(--spacing-xs);
  }
  
  .payment-desc {
    color: var(--text-secondary);
    font-size: var(--font-size-sm);
  }
}

.records-content {
  .records-filter {
    margin-bottom: var(--spacing-lg);
  }
  
  .records-list {
    max-height: 400px;
    overflow-y: auto;
  }
  
  .record-item {
    display: flex;
    align-items: center;
    padding: var(--spacing-md) 0;
    border-bottom: 1px solid var(--border-color);
    
    &:last-child {
      border-bottom: none;
    }
  }
  
  .record-icon {
    margin-right: var(--spacing-md);
    
    .el-icon {
      font-size: 20px;
    }
  }
  
  .record-info {
    flex: 1;
    
    .record-desc {
      font-size: var(--font-size-base);
      color: var(--text-primary);
      margin-bottom: 4px;
    }
    
    .record-meta {
      display: flex;
      gap: var(--spacing-md);
      font-size: var(--font-size-xs);
      color: var(--text-tertiary);
      
      .payment-method {
        color: var(--text-secondary);
      }
      
      .record-status {
        &.success {
          color: #67c23a;
        }
        
        &.failed {
          color: #f56c6c;
        }
        
        &.pending {
          color: #e6a23c;
        }
      }
    }
  }
  
  .record-amount {
    font-size: var(--font-size-lg);
    font-weight: bold;
    
    &.income {
      color: #67c23a;
    }
    
    &.expense {
      color: #f56c6c;
    }
  }
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: var(--spacing-md);
}

// 响应式设计
@media (max-width: 768px) {
  .wallet-page {
    padding: var(--spacing-md);
  }
  
  .balance-card {
    flex-direction: column;
    text-align: center;
    gap: var(--spacing-lg);
  }
  
  .wallet-stats {
    grid-template-columns: 1fr;
  }
  
  .quick-actions {
    grid-template-columns: 1fr;
  }
  
  .recharge-packages {
    grid-template-columns: 1fr;
  }
  
  .payment-methods {
    grid-template-columns: 1fr;
  }
}

.password-hint {
  font-size: 12px;
  color: #909399;
  margin-top: 4px;
}
</style> 